package 笔记.多线程;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author CHL
 * @ClassName: ReadWeiterDemo
 * @Description: 读写锁
 * @date 2023/11/3 16:51
 * @Version 1.0
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {

        // 参考文献：https://blog.csdn.net/qq_45699784/article/details/123569223?spm=1001.2014.3001.5502
        MyThreadlock myLock = new MyThreadlock();
        int num = 5;
        for (int i = 0; i < num; i++) {
            int finalI = i;
            new Thread(()->{
            myLock.write(String.valueOf(finalI), finalI);
            }).start();
        }

        for (int i = 0; i < num; i++) {

            int finalI = i;
            new Thread(()->{
                myLock.read(String.valueOf(finalI));

            }).start();
        }



    }

}

class MyThreadlock{
    // 处理同一块资源
    private volatile Map<String, Object> map = new HashMap<>();

    /**
     *
     * 加入最小颗粒锁,只会在最小程度上加锁
     * 加入lock锁后，当前线程写入操作时候不会有其他线程插入进来，则不会出现数据不一致问题
      */

    private ReadWriteLock lock = new ReentrantReadWriteLock();


    public void read(String key){
        // 读锁
//        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读取" + key);
            Object o = map.get(key);

//            System.out.println(Thread.currentThread().getName() + "读取完成");
        } finally {
            // 释放锁
//            lock.readLock().unlock();
        }

    }

    public void write(String key,Object value){
        // 写锁
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完成"+ JSON.toJSONString(map));
        } finally {
            // 释放锁
            lock.writeLock().unlock();
        }
    }
}
